package com.cnpc.netty.transfer;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;

public class TcpConnection {

	private Channel channel;

	public Channel connect(String host, int port) {
		doConnect(host, port);
		return this.channel;
	}

	private void doConnect(String host, int port) {
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			Bootstrap b = new Bootstrap();
			b.group(workerGroup);
			b.channel(NioSocketChannel.class);
			// 设置TCP协议的属性
			b.option(ChannelOption.SO_KEEPALIVE, true);
			b.option(ChannelOption.TCP_NODELAY, true);
			b.option(ChannelOption.SO_TIMEOUT, 5000);

			b.handler(new ChannelInitializer<SocketChannel>() {
				@Override
				public void initChannel(SocketChannel arg0) throws Exception {
					ChannelPipeline pipeline = arg0.pipeline();
					pipeline.addLast("decoder", new ByteArrayDecoder());
					pipeline.addLast("encoder", new ByteArrayEncoder());
					pipeline.addLast(new ClientPoHandlerProto());
				}
			});

			// Transfer.tcpc = Transfer.tcpBoot.connect(Transfer.tcpip,
			// Transfer.tcpport).sync().channel();
			ChannelFuture f = b.connect(host, port);
			f.addListener(new ConnectionListener());
			channel = f.sync().channel();

			Transfer.tcpBoot = b;
			Transfer.tcpc = channel;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}